package com.salt.core.oss.minio.utils;

import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * @Description
 * @Author salt
 * @Date 2022/11/4
 * @Version 1.0.1
 */
public class ImageUtil {


    /**
     * 图片流转base64编码
     * @param inputStream  文件流
     * @param formatName
     * @return
     */
    @SneakyThrows
    public static String imageToBase64(InputStream inputStream, String formatName) {
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        return imageToBase64(bufferedImage, formatName);
    }

    /**
     * 图片流转base64编码
     * @param bufferedImage 图片流
     * @param formatName 图片格式（png,jpg等）
     * @return 图片流的base64编码
     */
    @SneakyThrows
    public static String imageToBase64(BufferedImage bufferedImage, String formatName) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //Byte数组输出流
        //ImageIO.write(bufferedImage, "png", baos);
        // 利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流
        ImageIO.write(bufferedImage, formatName, baos); //
        byte[] byteArray = baos.toByteArray(); // 将Byte数组输出流转为数组
        // 生成base64编码
        String base64Image = Base64.encodeBase64String(byteArray);
        return base64Image;
    }
}
